#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Izidor Matusovic
# 2008-2009

import xmpp
import inspect
from datetime import datetime
from time import mktime, time
from math import floor
import random


class iyoBot():
	command_prefix = "cmd_"
	command_mark = "!"
	notification = {}

        def __init__(self, name, passwd, rooms=[]):
                self.jid = xmpp.protocol.JID(name)
                self.passwd = passwd
		self.cl = None

                self.rooms = rooms
                self.command = {}
                for (name, func) in inspect.getmembers(self):
			if inspect.ismethod(func) and name.startswith(self.command_prefix):
                    		self.command[self.command_mark+name[len(self.command_prefix):]] = func

                return
                

	def conf_message(self, sender, text):
		conf =  sender.getStripped()
		self.connect().send(xmpp.Message(conf, text, 'groupchat'))
		
	def leading_zero(self, time):
		#if time < 10:
			#return "0%d"%time
		#else:
		return "%d"%time

	def cmd_olinka(self, cl, message, args):
		msg = ['/me vzkazuje, že Izi má rád Olinku :-*', 'Čo je Olinka?', 'Růžová! ;)', 'iyo ťa zdraví', 'Áno, Olinka?', '/me je ráda, že si nanu niekto spomenie']
		self.conf_message(message.getFrom(), random.choice(msg))
	
	def cmd_iyo(self, cl, message, args):
		msg = ['Olinky milovaný kamarát', 'Izi', 'hodný Izi', 'môj stvoriteľ']
		self.conf_message(message.getFrom(), random.choice(msg))

	def cmd_krychle(self, cl, message, args):
		msg = ['Let`s see', 'hm.. možno áno', 'asi nie...', 'čo ja viem?', 'No to určite, čo by si nechcel(a)!', '(odpoved) && !odpoved || odpoved == rand()', 'Nejaká vtipná hláška', 'NIE!!!', 'Skôr nie.', 'Snažíš sa ma pobaviť? :-D', 'What? What? Whaaat?', '!(odpooved ~ 1)', 'return EXIT_FAILURE;', 'jj', 'ee', 'skôr nie', 'skôr áno', 'A čo si myslíš ty?', 'hm?', 'Čo zase chceš?!', 'Neotravuj, bolí ma hlava po fláme!', 'Doprdele, zase?', 'Neotravuj, nejsi tu sám a ja mám jenom 2 ruce!', 'jóoooooooo', 'Yeaaaaaaaaaah!', '*YES*', '*NO*', 'Spíš ne', 'Možno hej, možno nie', 'Tak absolutne netuším', 'Ak je vonku pekne...', 'Ak vonku prší, tak hej', 'Skús sa ma spýtať ešte raz ;)', 'jj 8-)', 'Nie je to dosť rigorózne!', 'A chodíš ty vôbec na prednášky?', 'No ešte som to neskúšal implementovať!']
		self.conf_message(message.getFrom(), random.choice(msg))

	def cmd_dobru(self, cl, message, args):
		if len(args.split()) >= 1:
			self.conf_message(message.getFrom(), "Dobru " + args.split()[0] + " aj tebe, " + message.getFrom().getResource())

	def cmd_dobre(self, cl, message, args):
		if len(args.split()) >= 1:
			self.conf_message(message.getFrom(), "Dobre " + args.split()[0] + " aj tebe, " + message.getFrom().getResource())

	def cmd_dobrou(self, cl, message, args):
		if len(args.split()) >= 1:
			self.conf_message(message.getFrom(), "Dobrou " + args.split()[0] + " aj tobě, " + message.getFrom().getResource())

	def cmd_dobry(self, cl, message, args):
		if len(args.split()) >= 1:
			self.conf_message(message.getFrom(), "Dobry " + args.split()[0] + " aj tebe, " + message.getFrom().getResource())

	def cmd_koule(self, cl, message, args):
		self.conf_message(message.getFrom(), "Radšej použí krychli: !krychle "+args+" ;)")

	def cmd_mas(self, cl, message, args):
		if args == "me rada?" and message.getFrom().getResource()=='Olinka':
			self.conf_message(message.getFrom(), "Olinka, mám ťa rada! :-*");

	def cmd_budes(self, cl, message, args):
		if args == "si se mnou povidat?":
			self.conf_message(message.getFrom(), "Prepáč, ale tu nie. Radšej napíš iyo-ovi pm-ku!");

	def cmd_mazlin(self, cl, message, args):
		msg = ['Olinky miláček', 'Pan Zlý', 'Olinky mačiatko', 'Olinky všechno', 'http://i38.tinypic.com/296f2gx.jpg']
		self.conf_message(message.getFrom(), random.choice(msg))

	def cmd_polo(self, cl, message, args):
		msg = ['polo je lolo', 'polo, nechaj ma! Ešte nechcem spadnút!','polo, ja chcem ešte žit!','Evil Harkonnen','Tenacious D rulezzz','polo ty sa zase nudíš']
		self.conf_message(message.getFrom(), random.choice(msg))
			
	def cmd_ruzova(self, cl, message, args):
		self.conf_message(message.getFrom(), "Zuzka: růžová!!!!!!!!")

	def cmd_vyber(self, cl, message, args):
		if args != "":
			self.conf_message(message.getFrom(), 'Môj výber je : '+random.choice(args.split()))

	def cmd_ruleta(self, cl, message, args):
		res = random.randint(0, 5)
		nick = message.getFrom().getResource()
		if res == 0:
			msg = ["%s is dead!"]
		else:
			msg = ["%s survives!"]

		self.conf_message(message.getFrom(), random.choice(msg)%(nick))

		if res == 0:
#Kill him!
			#xmpp.protocol.Iq('set', 'http://jabber.org/protocol/muc#admin', {'id':'blaBla'}, '1bit_vut@conf.netlab.cz', None, [], NS_CLIENT, )
			#  def __init__(self, typ=None, queryNS=None, attrs={}, to=None, frm=None, payload=[], xmlns=NS_CLIENT, node=None): 
			cl.send('''<iq type="set" to="1bit_vut@conf.netlab.cz" id="ab1ea" >
<query xmlns="http://jabber.org/protocol/muc#admin">
<item nick="'''+nick+'''" role="none" />
</query>
</iq>''')

	def cmd_fanda(self, cl, message, args):
		self.conf_message(message.getFrom(), 'Nazdar fando! :-)')

	def cmd_juan(self, cl, message, args):
		self.conf_message(message.getFrom(), 'Ahojky Juane! Jak se dnes vede?')

	def cmd_cerna(self, cl, message, args):
		self.conf_message(message.getFrom(), 'černá - polova metálová barva :-D')

	def cmd_kde(self, cl, message, args):
		if args == "je izi?":
			msgs = ['Izi sa zase niekde fláka... prepáč Olinka :-(']
			self.conf_message(message.getFrom(), random.choice(msgs))

	def cmd_zuzka(self, cl, message, args):
		self.conf_message(message.getFrom(), "Zuzka, aj teba mám rada!")

	def cmd_salto(self,cl, message, args):
		self.conf_message(message.getFrom(), "Dvojité salto vzad cez obruč")

	def cmd_grep(self,cl, message, args):
		msg = ['Zuzka: dobrú chuť!', 'Zuzka: neprežeň to!', 'Grep Zuzkin milovaný', "Zuzka: ty prežiješ ten absták!"]
		self.conf_message(message.getFrom(), random.choice(msg))

	def cmd_weri(self,cl, message, args):
		msg = ["Poznám pravdu o Weri-m!", "Weri: ja sa nechávam zbalit :-D", "Weri nemá nikdy dost miesta na porno!"]
		self.conf_message(message.getFrom(), random.choice(msg))

	def cmd_help(self, cl, message, args):
		self.conf_message(message.getFrom(), "Skutočná cesta vedie cez príkazový riadok bez helpu!\nKeby niečo, tak napíš !timer ;)");

	def cmd_stromecek(self, cl, message, args):
		self.conf_message(message.getFrom(), "Zuzkin stromeček: http://i38.tinypic.com/2kqakw.jpg");

	def cmd_upozorni(self, cl, message, args):
		room = message.getFrom().getStripped()
		sender = message.getFrom().getResource();

		if args == "":
			self.conf_message(message.getFrom(), u"%s: musíš zadať nick užívateľa, na ktorého príchod chceš upozrniť!" % (sender))
		else:
			nick = args
			wanted = args.lower()
			if wanted not in self.notification:
				self.notification[wanted] = []

			self.notification[wanted].append(sender)
			self.conf_message(message.getFrom(), u"%s: upozorním ťa, keď %s sem dorazí!" % (sender, nick));
		
	def cmd_timer(self,cl, message, args):
		t1 = round(mktime(datetime(2009, 1, 5, 12, 00).timetuple()))
		msg_end = "Koniec... :-P"
			
		#print "'%s'" % args
		t2 = round(time())
		delta = t1-t2
		if(delta < 0):
			msg = msg_end
		else:
			#print delta

			h = floor(delta/3600)
			delta = delta - h*3600
			m = floor(delta / 60)
			s = floor(delta - 60*m)

			cas = ""
			if h > 0:
				cas = cas + "%sh"%(self.leading_zero(h))
			cas = cas + " %sm %ss"%(self.leading_zero(m), self.leading_zero(s))

			msg = "Do konca prázdnin zostáva už len %s!!!! *YEAH*" % cas
		
		self.conf_message(message.getFrom(), msg);

	#def cmd_school(self,cl, message, args):

        def log(self, message):
                print "Log: %s" % message

	def get_true_jid(self, jid):
		tjid=jid[1]+'/'+jid[2]
	#        print GROUPCHATS
    		if xmpp.GROUPCHATS.has_key(jid[1]):
        		return tjid
    		else:
        		return jid[1]

	def incomming_message(self, cl, event):
		body = event.getBody()

		print "---%s"%(event.getFrom())
		
		if not body or not body.startswith(self.command_mark):
			return

		if ' ' in body:
			command, args = body.split(' ', 1)
		else:
			command, args = body, ''

		command = command.lower()
		
		if self.command.has_key(command):
			self.command[command] (cl, event, args)


	def presence(self, cl, event):
		room=event.getFrom().getStripped()
	    	nick=event.getFrom().getResource()

	    	if event.getType()!='unavailable':
			print "%s sa prihlasil\n" % nick

        def connect(self):
		if self.cl == None:
			cl = xmpp.Client(self.jid.getDomain(), debug=[])
			if not cl.connect():
				self.log('Unable to connect to server.')
				return None

			if not cl.auth(self.jid.getNode(), self.passwd, self.jid.getResource()):
				self.log('Unable to authorize')
				return None

			for room,passwd in self.rooms:
				p=xmpp.Presence(to='%s'%room)
				p.setTag('x',namespace=xmpp.NS_MUC).setTagData('password',passwd)
				self.log('Connected to %s.'%room)
				cl.send(p)


			cl.RegisterHandler( 'message', self.incomming_message)
			cl.RegisterHandler( 'presence', self.presence)
			cl.sendInitPresence()

			self.cl = cl
			return self.cl
		else:
			return self.cl

	def chat_message(self, sender, text):
		conf =  sender.getStripped()
		self.connect().send(xmpp.Message(conf, text, 'groupchat'))

	def sendMsgs(self):
		jid = xmpp.protocol.JID("1bit_vut@conf.netlab.cz")
		fileName="msgs.txt"
		f = open(fileName, "r")
		for line in f.readlines():
			print "niečo posielam - "+line
			self.chat_message(jid, line)
		f.close()

		f = open(fileName, "w")
		f.close()


	def serve(self):
		if self.connect():
			self.log('Bot start serving')
		else:
			self.log('Unable to start bot. Quiting')
			return

		while True:
			try:
				self.connect().Process(1)
				#self.sendMsgs()
				pass
			except KeyboardInterrupt:
				self.log('Bot interrupted by user. Quiting.')
				self.connect().disconnect()
				break

#name=sys.argv[1]
#rooms=sys.argv[2]
#pwd=sys.argv[3]
#room_name=sys.argv[4]

name = 'xxx'
passwd = 'xxx'
#rooms = []
#rooms = [('bot@conf.netlab.cz/iyoBot', 'passwd')]
rooms = [("1bit_vut@conf.netlab.cz/Nora", '')]
bot = iyoBot(name, passwd, rooms)
bot.serve()
